package service

import (
	"context"
	"duoke/model"
	"duoke/utils/gjson"
	"duoke/utils/gmd5"
	"duoke/utils/redislib"
	TencentCloud "duoke/utils/tencent_cloud"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

var TencentStore = new(tencentStoreService)

type tencentStoreService struct{}

func (s *tencentStoreService) Result(req *model.Result) (*model.RspResult, error) {
	var m model.RspResult
	key, err := gmd5.Encrypt(req.TbImage + req.FfImage + req.FfImage)
	fmt.Println(key)
	if err != nil {
		return nil, err
	}
	get := redislib.Redis.Get(context.Background(), key)
	if get.Val() != "" {
		if err = json.Unmarshal([]byte(get.Val()), &m); err != nil {
			return nil, err
		}
		return &m, nil
	}
	if "" == req.TfImage && "" == req.FfImage && "" == req.TbImage {
		return nil, errors.New("舌照图片，面照图片，舌下脉络图片必须选择一个")
	}
	result, err := TencentCloud.TencentStore.NewConfig().Result(req)
	if err != nil || len(result) == 0 {
		return nil, err
	}
	if err = json.Unmarshal(result, &m); err != nil {
		return nil, err
	}
	if m.Code != 20000 && m.Success != true {
		return nil, errors.New(m.Msg)
	}
	redislib.Redis.Set(context.Background(), key, result, 3600*time.Minute)
	return &m, nil
}
func (s *tencentStoreService) Report(req *model.ReqReport) (*model.RspReport, error) {
	var m model.RspReport
	if "" == req.SessionId {
		return nil, errors.New("sessionId不能为空")
	}
	encrypt, err := gmd5.Encrypt(req.Answers)
	if err != nil {
		return nil, err
	}
	redisKey := req.SessionId + ":" + encrypt
	val := redislib.Redis.Get(context.Background(), redisKey).Val()
	if val != "" {
		gjson.Json2StructOrMap(val, &m)
		return &m, nil
	}
	result, err := TencentCloud.TencentStore.NewConfig().Report(req)
	if err != nil {
		return nil, err
	}
	if err = json.Unmarshal(result, &m); err != nil {
		return nil, err
	}
	if m.Code != 20000 && m.Success != true {
		return nil, errors.New(m.Msg)
	}
	redislib.Redis.Set(context.Background(), redisKey, result, 3600*time.Minute)
	return &m, nil
}
